package com.lanou.moving.net;

import android.util.Log;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.lanou.moving.entity.SingerInfo;
import com.lanou.moving.entity.SingerSimilar;

import org.json.JSONObject;

/**
 * 网络拉取得工具类
 */
public class HttpHelper implements NetDataWhat {
    private RequestQueue requestQueue;//请求队列
    private NetDataCallBack netDataCallBack;//返回数据的接口

    public HttpHelper(NetDataCallBack netDataCallBack) {
        this.netDataCallBack = netDataCallBack;
        requestQueue = MyQueue.getInstance().getVolleyQueue();
    }

    /**
     * 歌手详情 相似歌手接口
     */
    public void getSingerSimilar(int singer_id) {
        String singer_similar_start = "http://api.dongting.com/sim/singer/";
        String singer_similar_end = "/similarity?utdid=VPxgnHgoEZ8DALFJVV09NJNS";
        String path = singer_similar_start + singer_id + singer_similar_end;
        Log.d("dada", path);
        getNetData(path, WHAT_SINGER_SIMILAR);
    }

    /**
     * 歌手详情 歌手信息接口
     */
    public void getSingerInfo(int singer_id) {
        String singer_info_start = "http://api.dongting.com/song/singer/";
        String singer_info_end = "?utdid=VPxgnHgoEZ8DALFJVV09NJNS&detail=true";
        String path = singer_info_start + singer_id + singer_info_end;
        getNetData(path, WHAT_SINGER_INFO);
    }

    //网络数据拉取
    private void getNetData(String path, final int what) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(path,
                null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                /**成功，调用接口的成功方法
                 * @pargm response 解析之后的数据实体类
                 */
                netDataCallBack.netSuccess(what, resolution(what, response));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //失败，调用接口的失败方法
                netDataCallBack.netError(what);
            }
        });
        requestQueue.add(jsonObjectRequest);//加入到请求队列
    }

    //解析方法，将Json数据解析成实体类
    private Object resolution(int what, JSONObject response) {
        Object object = null;
        Gson gson = new Gson();
        switch (what) {
            case WHAT_SINGER_SIMILAR:
                object = gson.fromJson(response.toString(), SingerSimilar.class);
                break;
            case WHAT_SINGER_INFO:
                object = gson.fromJson(response.toString(), SingerInfo.class);
                break;
        }
        return object;
    }


}
